const productService = require('../../../services/productService');
const { successRes, errorRes } = require('../../../utils/responseHandler');

// 获取商品列表（支持分页和条件查询）
const getList = async (req, res) => {
    try {
        const params = req.query;
        const products = await productService.getAllProductsService(params);
        successRes(res, products);
    } catch (err) {
        errorRes(res, err.message);
    }
};

// 获取单个商品详情
const getDetail = async (req, res) => {
    try {
        const productId = req.params.id;
        const product = await productService.getProductById(productId);
        successRes(res, product);
    } catch (err) {
        errorRes(res, err.message);
    }
};

// 创建或更新商品
const createOrUpdate = async (req, res) => {
    console.log(req.body);
    try {
        const productId = req.body.id;
        let product;
        if (productId) {
            // 更新商品
            product = await productService.updateProduct(productId, req.body);
        } else {
            // 创建新商品
            product = await productService.addProduct(req.body);
        }
        successRes(res, product);
    } catch (err) {
        errorRes(res, err.message);
    }
};

// 删除商品
const deleteProduct = async (req, res) => {
    try {
        const productId = req.params.id;
        await productService.deleteProductService(productId);
        successRes(res, { message: 'Product deleted successfully' });
    } catch (err) {
        errorRes(res, err.message);
    }
};

module.exports = {
    getList,
    getDetail,
    createOrUpdate,
    deleteProduct
};
